<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/12/18
 * Time: 9:37
 */
namespace app\api\controller;
use think\Db;
class Shop extends Base {

    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            echo json_encode(['status'=>301,'msg'=>"Token失效！请重新登录！"]);
            exit;
        }
    }

    /***
     * @return \think\response\Json
     * 商城首页
     */
    public function index(){
        $page = input('param.page')?input('param.page'):1;
        $num = 10;
        $limit = $page-1;
        $where['good_status'] =1;
        $res = Db::table('up_goods')
            ->field('good_id,good_thumb,good_name,good_price')
            ->limit($limit*$num,$num)
            ->where($where)
            ->select();
      return json(array('status'=>200,'msg'=>$res));
    }
    /***
     * 品牌
     */
    public function brand(){
        $table = 'up_pinpai';
        $field = 'p_id,p_name';
        $where['p_status'] =1;
        $res = $this->selectList($table,$field,$where);
        return json(array('status'=>200,'msg'=>$res));
    }

    /***
     * @return \think\response\Json
     * 型号
     */
    public function  version(){
        $table = 'up_xinghao';
        $field = 'x_name,x_id';
        $where['x_status'] =1;
        $res = $this->selectList($table,$field,$where);
        return json(array('status'=>200,'msg'=>$res));
    }

    /**
     * @return \think\response\Json
     * 搜索接口
     */
    public function selectShop(){
        $keyword = input('param.keyword')?input('param.keyword'):'';
        $page = input('param.page')?input('param.page'):1;

        if($keyword!=''){
            $where['good_name'] = array('like',"%$keyword%");
        }
        $where['good_status'] =1;
        $num = 10;
        $limit = $page-1;
        $res = Db::table('up_goods')
            ->field('y_price,good_id,good_thumb,good_name,good_price')
            ->limit($limit*$num,$num)
            ->where($where)
            ->select();
        return json(array('status'=>200,'msg'=>$res));
    }

    /**
     * @return \think\response\Json
     * 全部  品牌 型号筛选
     *
     */
    public function selectShopType(){
        $page = input('param.page')?input('param.page'):1;
        $type = input('param.type')?input('param.type'):1;  //   1全部   2品牌  3型号
        $id = input('param.id');  //   1全部   2品牌  3型号
       if ($type==2){
            $where['good_pinpai'] = $id;
        }elseif ($type==3){
            $where['good_xinghao'] = $id;
        }
        $num = 10;
        $limit = $page-1;
        $where['good_status'] =1;
        $res = Db::table('up_goods')
            ->field('good_id,good_thumb,good_name,good_price,y_price')
            ->limit($limit*$num,$num)
            ->where($where)
            ->select();
        return json(array('status'=>200,'msg'=>$res));
    }
    /***
     * @return \think\response\Json
     * 详情
     */
    public function shopDetail(){
        extract(input());
        $good_id  = input('param.good_id');
        $type  = input('param.type')?input('param.type'):1;//   1商品详情   2商品参数
        $where['good_id'] = $good_id;
        if($type==1){
            $res = Db::table('up_goods')->alias('a')
                                ->join('up_pinpai up','up.p_id = a.good_pinpai','left')
                                ->join('up_xinghao ux','ux.x_id = a.good_xinghao','left')
                                ->where($where)
                                ->field('a.good_thumb,a.good_image,up.p_name,ux.x_name,a.good_ss_time,a.good_id,a.good_name,a.good_price,a.y_price,a.good_content')
                                ->find();
        }elseif ($type==2){
            $field ='*';
            $res = Db::table('up_goods')->field($field)->where($where)->find();
        }
        //购物车数量
        $where1['car_userid'] = $user_id;
        $car_number = Db::table('up_shopping_car')->where($where1)->sum('car_number');
        //
        $whereMap['l_user_id'] = $user_id;
        $whereMap['l_good_id'] = $good_id;
        $result = Db::table('up_like')->where($whereMap)->find();
        if($result){
            $res['like'] = 1;
        }else{
            $res['like'] = 2;
        }
        $res['car_number'] = $car_number;
        return json(array('status'=>200,'msg'=>$res));
    }

    /***
     * @return \think\response\Json
     * 商品banner图
     */
    public function shopBanner(){
        $good_id  = input('param.good_id');
        $where['good_id'] = $good_id;
        $res = Db::table('up_goods')
            ->field('good_id,good_image')
            ->where($where)
            ->find();
        return json(array('status'=>200,'msg'=>$res));
    }

    /***
     * @return \think\response\Json
     * 收藏接口
     */
    public function shopLike(){
        extract(input());
        $good_id  = input('param.good_id');
        $where['l_user_id'] = $user_id;
        $where['l_good_id'] = $good_id;
        $result = Db::table('up_like')->where($where)->find();
        if($result){//证明已经收藏
            $res = Db::table('up_like')->where($where)->delete();
            if($res){
                return json(array('status'=>200,'msg'=>'取消收藏成功'));
            }else{
                return json(array('status'=>200,'msg'=>'取消收藏失败'));
            }
        }else{//没有收藏
            $data['l_user_id'] = $user_id;
            $data['l_good_id'] = $good_id;
            $data['l_time'] = date('Y-m-d H:is',time());
            $res = Db::table('up_like')->insertGetId($data);
            if($res){
                return json(array('status'=>200,'msg'=>'收藏成功'));
            }else{
                return json(array('status'=>200,'msg'=>'收藏失败'));
            }
        }

    }
    /***
     * @return \think\response\Json
     * 购物车数量
     */
    public function carNum(){
        extract(input());
        $where['car_userid'] = $user_id;
        $car_number = Db::table('up_shopping_car')->where($where)->sum('car_number');
        return json(array('status'=>200,'msg'=>$car_number));
    }


    /**
     * @return \think\response\Json
     * 购物车列表
     */
    public function carList(){
        extract(input());
        $page = input('param.page')?input('param.page'):1;
        $type = input('param.type');
        if($type==1){
            $field = 'ug.good_name,ug.good_thumb,ug.good_price,a.car_number,a.car_id';
        }elseif ($type==2){
            $field = 'ug.good_name,ug.good_thumb,ug.y_price as good_price,a.car_number,a.car_id';
        }

        $num = 10;
        $limit = $page-1;
        $where['car_userid'] =$user_id;
        $res = Db::table('up_shopping_car')
            ->alias('a')
            ->join('up_goods ug','ug.good_id=a.car_goodid','left')
            ->field($field)
            ->limit($limit*$num,$num)
            ->where($where)
            ->select();
        return  json(array('status'=>200,'msg'=>$res));
    }

    /***
     * @return \think\response\Json
     * 删除购物车
     */
    public function shopDel(){
        $car_id = input('param.car_id');
        $where['car_id'] = array('IN',$car_id);
        $res = Db::table('up_shopping_car')->where($where)->delete();
        if($res){
            return  json(array('status'=>200,'msg'=>"删除成功"));
        }else{
            return  json(array('status'=>200,'msg'=>"删除失败"));
        }
    }

    /***
     * @return \think\response\Json
     * 购物车列表修改数量
     */
    public function shopUpdate(){
        $car_id = input('param.car_id');
        $num = input('param.num');   //1加   2减
        $where['car_id'] = $car_id;
        $res = Db::table('up_shopping_car')->where($where)->setField('car_number',$num);
        if($res){
            return  json(array('status'=>200,'msg'=>"成功"));
        }else{
            return  json(array('status'=>100,'msg'=>"失败"));
        }
    }

    /***
     * @return \think\response\Json
     */
    public function shopDetailNum(){
        extract(input());
        $good_id = input('param.good_id');
        $where['car_userid'] = $user_id;
        $where['car_goodid'] = $good_id;
        $car_number = Db::table('up_shopping_car')->where($where)->find();
        return  json(array('status'=>200,'msg'=>$car_number));
    }

    /***
     * @return \think\response\Json
     * 添加购物车
     */
    public function shopAddCar(){
        extract(input());
        $good_id = input('param.good_id');
        $car_number = input('param.car_num');
        $where['car_userid'] = $user_id;
        $where['car_goodid'] = $good_id;
        $result = Db::table('up_shopping_car')->where($where)->find();
        if($result['car_id']!=''){//证明已经该用户该商品已经添加了
            $res = Db::table('up_shopping_car')->where($where)->setInc('car_number',$car_number);
        }else{
            //查询这个商品的品牌
            $good_pinpai = Db::table('up_goods')->where('good_id',$good_id)->value('good_pinpai');
            $data['car_userid'] =$user_id;
            $data['car_goodid'] =$good_id;
            $data['car_number'] =$car_number;
            $data['car_time'] =date('Y-m-d H:i:s',time());
            $data['car_pinpai_id'] =$good_pinpai;
            $res = Db::table('up_shopping_car')->insertGetId($data);
        }
        if($res){
            return  json(array('status'=>200,'msg'=>"添加成功"));
        }else{
            return  json(array('status'=>200,'msg'=>"添加失败"));
        }
    }

    /***
     * @return \think\response\Json
     * 填写订单
     */
    public function addShopOrder(){
        extract(input());
        $page = input('param.page')?input('param.page'):1;
        $type = input('param.type');
        $num = 10;
        $limit = $page-1;
        if($type==1){
            $field = 'ug.good_name,ug.good_thumb,ug.good_price,a.car_number,a.car_id';
        }elseif ($type==2){
            $field = 'ug.good_name,ug.good_thumb,ug.y_price as good_price,a.car_number,a.car_id';
        }
        $car_id = input('param.car_id');
        $where['car_id'] = array('IN',$car_id);
        $res = Db::table('up_shopping_car')
            ->alias('a')
            ->join('up_goods ug','ug.good_id=a.car_goodid','left')
            ->field($field)
            ->limit($limit*$num,$num)
            ->where($where)
            ->select();
        $whereMap['user_id'] = $user_id;
        $userInfo = Db::table('up_u_user')->where($whereMap)->field('user_username,user_phone,user_address')->find();
        $res['user_phone'] = $userInfo['user_phone'];
        $res['user_address'] = $userInfo['user_address'];
        $res['user_username'] = $userInfo['user_username'];
        return  json(array('status'=>200,'msg'=>$res));
    }

    /****
     * 提交订单-商品判断代理
     */
    public function desire(){
        extract(input());
//        $user_id = 69;
        $where['user_id'] =$user_id;
        $Info = Db::table('up_u_user')->where($where)->field('user_shi,user_type')->find();
        if($Info['user_type']==1){//用户端
            $car_id = input('param.car_id');
//            $car_id = 638;
            //先查找这个用户属于哪个市的
            $where1['user_shi'] = $Info['user_shi'];
            $where1['user_type'] = 2;
            $where1['user_status'] = 1;
            //运营端的代理的品牌
            $user_pinpai_id = Db::table('up_u_user')->where($where1)->column('user_pinpai_id');
            //查询用户购物车的商品品牌和商品名称
            $where2['a.car_id'] = array('IN',$car_id);
            $where2['a.car_userid'] = $user_id;
            $car_pinpai_id = Db::table('up_shopping_car')->alias('a')
                ->join('up_goods ug','ug.good_id = a.car_goodid','left')
                ->where($where2)
                ->field('ug.good_name,a.car_pinpai_id')
                ->select();
            foreach ($car_pinpai_id as $key=>$vo){
                if(!in_array($vo['car_pinpai_id'],$user_pinpai_id)){
                    return  json(array('status'=>100,'msg'=>$vo['good_name']));
                }
            }
            return  json(array('status'=>200,'msg'=>"成功"));
        }else{//运行端
            return  json(array('status'=>200,'msg'=>"成功"));
        }
    }
    /***
     * 提交订单
     */
    public function postOrder()
    {
        extract(input());
        $order_number = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);//订单编号
        $car_id = input('param.car_id')?input('param.car_id'):'614,615';
        $where['car_id'] = array('IN',$car_id);
        $where['car_userid'] = $user_id;
        //查询购物情况
        $res = Db::table('up_shopping_car')->where($where)->select();
        //用户信息
        $userInfo = Db::table('up_u_user')->where('user_id',$user_id)->field('user_shi,user_ssq_str,user_type,user_username,user_phone,user_address')->find();
            // 启动事务
            Db::startTrans();
            $pirce = 0;//order订单表中的总价格初始变量
            $num = 0;//order订单表中的数量初始变量
            foreach ($res as $key=>$vo){
                //查询这个商品的价格
                $goodInfo = Db::table('up_goods')
                    ->where('good_id',$vo['car_goodid'])
                    ->field('good_pinpai,y_price,good_id,good_thumb,good_price,good_name')
                    ->find();
                if($userInfo['user_type']==2){//运行端
                    $shop_price = $goodInfo['y_price'];//运行端价格
                }else{//用户端
                    $shop_price = $goodInfo['good_price'];//用户端价格
                }
                $pirce += $shop_price*$vo['car_number'];//总价格
                $num += $vo['car_number'];//总数量
                /***************插入订单详情开始*************/
                $dataInfo['oi_good_id'] = $vo['car_goodid'];//商品ID
                $dataInfo['oi_price'] = $shop_price;//购买商品的单价格
                $dataInfo['oi_all_price'] = $shop_price*$vo['car_number'];//购买每个商品的总价格
                $dataInfo['oi_num'] = $vo['car_number'];//购物数量
                $dataInfo['oi_good_name'] = $goodInfo['good_name'];
                $dataInfo['oi_good_thumb'] = $goodInfo['good_thumb'];
                $dataInfo['oi_pay_time'] = date('Y-m-d H:i:s',time());
                $dataInfo['oi_pinpai_id'] = $goodInfo['good_pinpai'];
//                $dataInfo['oi_daili_id'] = ;
                //返回ID
                $order_info_id = Db::table('up_order_info')->insertGetId($dataInfo);
                $dataList[]=$order_info_id;
                /************结束****************/
            }
        /************插入订单表开始***************/
        if($userInfo['user_type']==2){//运行端
            $order_type_on = 2;//运行端价格
        }else{//用户端
            $order_type_on = 1;//用户端价格
        }
        $data['order_number'] = $order_number;//订单编号
        $data['order_userid'] = $user_id;//用户ID
        $data['order_num'] = $num;//商品数量
        $data['order_address'] = $userInfo['user_ssq_str'].$userInfo['user_address'];//商收货人详情地址
        $data['order_address_phone'] = $userInfo['user_phone'];//收货手机号码
        $data['order_address_name'] = $userInfo['user_username'];//收货人姓名
        $data['order_user_pay'] = $pirce;//总价格
        $data['order_time'] = date('Y-m-d H:i:s',time());//下单时间
        $data['order_type_on'] = $order_type_on;//1用户端订单  2运行端订单
        $result = Db::table('up_order')->insertGetId($data);//插入订单表
        //order_info查询条件
        $where1['oi_id'] = array('IN',implode(',',$dataList));
        /*****************结束******************/





        /*********************结束***********************************/
        $data1['oi_order_id'] = $result;
        $aa = Db::table('up_order_info')->where($where1)->update($data1);
        $where2['car_id'] = array('IN',$car_id);
        $bb = Db::table('up_shopping_car')->where($where2)->delete();

        $All = [];
        /*****************分组查询order_info表********************/
        //分组查询这个订单下面的品牌
        if($userInfo['user_type']==1){//用户端拆分订单
            $Info1 = Db::table('up_order_info')->where($where1)->field('oi_pinpai_id')->group('oi_pinpai_id')->select();
            foreach ($Info1 as $key1=>$vo1){
                $wh11['user_shi'] = $userInfo['user_shi'];
                $wh11['user_type'] = 2;
                $wh11['user_status'] = 1;
                $wh11['user_pinpai_id'] = $vo1['oi_pinpai_id'];
                //查询这个市的品牌代理的用户id
                $user_pinpai_id = Db::table('up_u_user')->where($wh11)->value('user_id');
                $wh1['oi_order_id'] = $result;
                $wh1['oi_pinpai_id'] = $vo1['oi_pinpai_id'];
                $oi_num = Db::table('up_order_info')->where($wh1)->sum('oi_num');
                $oi_all_price = Db::table('up_order_info')->where($wh1)->sum('oi_all_price');

                $resAll['order_c_number'] =$order_number;
                $resAll['order_c_userid'] =$user_id;
                $resAll['order_c_num'] =$oi_num;
                $resAll['order_c_user_pay'] =$oi_all_price;
                $resAll['order_c_address'] =$userInfo['user_ssq_str'].$userInfo['user_address'];
                $resAll['order_c_address_phone'] =$userInfo['user_phone'];
                $resAll['order_c_address_name'] =$userInfo['user_username'];
                $resAll['order_c_time'] =date('Y-m-d H:i:s',time());
                $resAll['order_c_pinpai_id'] =$vo1['oi_pinpai_id'];
                $resAll['order_id'] =$result;
                $resAll['order_c_daili_id'] =$user_pinpai_id;//所属代理
                $All[] = $resAll;
            }
            Db::table('up_order_children')->insertAll($All);
        }
            foreach ($dataList as $kk=>$vv){
                $rr = Db::table('up_order_info')->where('oi_id',$vv)->field('oi_order_id,oi_pinpai_id')->find();
                $map['order_id'] = $rr['oi_order_id'];
                $map['order_c_pinpai_id'] = $rr['oi_pinpai_id'];
                $order_c_id = Db::table('up_order_children')->where($map)->value('order_c_id');
                Db::table('up_order_info')->where('oi_id',$vv)->update(['oi_order_chil_id' => $order_c_id]);
            }
        if($aa&&$bb){
            Db::commit();
//            if($userInfo['user_type']==1){
//                $str = array();
//                //极光推送
//                try{
//                    foreach($All as $ke => $val){
//                        $user_id = (string)$val['order_c_daili_id'];
//                        array_push($str, $user_id);
//                    }
//                    $this->Jpush(1, $str, '您收到一个新订单', ['type' => '']);
//                }catch(\Exception $e){
//                }
//            }
            return  json(array('status'=>200,'msg'=>$result));
        }else{
            Db::rollback();//回滚
            return  json(array('status'=>100,'msg'=>"提交订单失败"));
        }
    }

    /*****
     * @return \think\response\Json
     *
     */
    public function hot(){
        $res = Db::table('up_hot')->select();
        return json(array('status'=>200,'msg'=>$res));
    }

    /****
     *提交订单返回数据
     */
    public function payment(){
        $orderId = input('param.id');
        $res = Db::table('up_order')
            ->where('order_id',$orderId)
            ->field('order_id,order_number,order_user_pay,order_time')
            ->find();
        return json(array('status'=>200,'msg'=>$res));
    }


    public function balance(){
        extract(input());
        $order_id = input('param.order_id');
        $money = input('param.money');
        $user_money = Db::table('up_u_user')->where('user_id',$user_id)->value('user_money');
        $user_type = Db::table('up_u_user')->where('user_id',$user_id)->value('user_type');
        if($money>$user_money){
            return json(array('status'=>201,'msg'=>"余额不足"));
        }else{
            Db::startTrans();
            $data['order_type'] =3;
            $data['order_paytime'] =date('Y-m-d H:i:s',time());
            $data['order_status'] =2;
            $dd = true;
            $res = Db::table('up_order')->where('order_id',$order_id)->update($data);
            if($user_type == 1){
                $dataOrders['order_c_status'] = 2;
                $abc = Db::table('up_order_children')->where('order_id',$order_id)->update($dataOrders);
                if($abc){
                    $dd  = true;
                }else{
                    $dd = false;
                }
            }



            $res1 = Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_money',$money);

            $Info['ji_user_id'] = $user_id;
            $Info['ji_num'] = date('YmdHis') . str_pad(mt_rand(1, 99999999), 6, '0', STR_PAD_LEFT).$user_id;
            $Info['ji_title'] = '电池购买';
            $Info['ji_type'] =2;
            $Info['ji_from'] = 4;
            $Info['ji_money'] = $money;
            $Info['ji_time'] = date('Y-m-d H:i:s',time());
            $Info['ji_status'] = 2;
            Db::table('up_jilu')->insertGetId($Info);
            if($res&&$res1&&$dd){
                $order_number = Db::table('up_order')
                    ->where('order_id', $order_id)
                    ->value('order_number');
                //给自己推送
                try{
                    $user_id = (string)$user_id;
                    $str = '您编号为' . $order_number . '的订单已支付成功';
                    $this->Jpush(1, $user_id, $str, ['type' => '']);
                }catch(\Exception $e){
        
                }
                //如果是用户订单，需给对应代理推送
                if($user_type == 1){
                    $daili_ids = Db::table('up_order_children')
                        ->where('order_c_number', $order_number)
                        ->field('order_c_daili_id')
                        ->select();
                    $ids = [];
                    foreach($daili_ids as $ke => $val){
                        $daili_id = (string)$val['order_c_daili_id'];
                        array_push($ids, $daili_id);
                    }
                    $this->Jpush(1, $ids, '您收到一个新订单', ['type' => '']);
                }
                Db::commit();
                return json(array('status'=>200,'msg'=>"支付成功"));
            }else{
                Db::rollback();//回滚
                return json(array('status'=>201,'msg'=>"支付失败"));
            }
        }
    }
}
